$package("wstuo.user");
$import('wstuo.orgMge.organizationTreeUtil');
$import('wstuo.user.userPwdUpdate');
$import('wstuo.includes');
$import('basics.index');
//$import('wstuo.config.systemGuide.systemGuide');
$import('wstuo.orgMge.organizationTree');
/**  
 * @author QXY  
 * @constructor users
 * @description 用户管理主函数.
 * @date 2011-02-25
 * @since version 1.0 
 */
wstuo.user.user=function(){
	var operator;
	this.userRoleIds = new Array();
	this.mydata = new Array();
	this.userGrids=[];
	this.loadUserRole=0;
	this.ProxyType=0;
	this.Proxyshow=0;
	this.usedTechnicianNumber=10000;
	this.user_search_selectData_flag=true;
	
	return{

		countTc:function(){
			/*$.post('user!countTechnician.action',function(data){
				$('#TechnicianNumber_toolbar').text(i18n.toolbar_echnician_License.replace('{0}',technicianNumber).replace('{1}',data).replace('{0}',data).replace('{2}',technicianNumber-data));
				usedTechnicianNumber=data;
			});*/
		
		},
		
		/**
		 * @description 状态格式化.
		 * @param cellvalue 当前列
		 * @param options 下拉选项
		 */
		userStateFormat:function(cellvalue, options){
			if(cellvalue){
				return i18n.common_enable;
			}
			else{
				return i18n.common_disable;
			}
		},
		/**
		 * @description 动作格式化.
		 */
		userGridFormatter:function(cell,opt,data){
			return $('#userToolbarAct').html().replace(/{userId}/g,opt.rowId);
		},
		
		/**
		 * @description 性别格式化
		 * @param cell 当前列值
		 * @param opt 下拉选项
		 * @param data 行数据
		 * @private
		 */
		sexForma:function(cell,opt,data){
          if(cell){
            return i18n.label_user_man;
          }else{
			return i18n.label_user_woman;
          }
		},
		
		/**
		 * @description 加载用户列表.
		 */
		showUserGrid:function(){
			var params = $.extend({},jqGridParams, {	
				url:'user!find.action?userQueryDto.companyNo='+companyNo,
				colNames:['ID',i18n.title_user_loginName,i18n.title_user_lastName,i18n.title_user_firstName,i18n.label_user_sex,i18n.title_user_org,
                        i18n.label_userOwnerGroup,
                        i18n.title_user_phone,i18n.title_user_mobile,i18n.title_customer_email,i18n.title_org_role,i18n.common_state,i18n.label_user_holidayStatus,
                          '‘’','','‘’','','','','','','','','','','',i18n.common_action],
                colModel:[
                        {name:'userId',align:'center',width:40},
                        {name:'loginName',align:'left',width:80},
                        {name:'firstName',align:'center',width:80},
                        {name:'lastName',align:'center',width:80},
                        {name:'sex',align:'center',width:30,formatter:wstuo.user.user.sexForma,hidden:true},
                        {name:'orgName',align:'left',index:'orgnization',width:120},
                        {name:'belongsGroupStr',index:'belongsGroup',align:'left',width:120,formatter:function(cellvalue, options, rowObject){
							 return rowObject.belongsGroupStr.substring(0,rowObject.belongsGroupStr.length-1);
						   }},
                        {name:'phone',align:'left',width:90},
                        {name:'moblie',align:'left',width:90},
                        {name:'email',align:'left',width:130},
                        {name:'roles',align:'left',width:120},
                        {name:'userState',align:'center',width:40,formatter:wstuo.user.user.userStateFormat},
                        {name:'holidayStatus',align:'center',width:60,formatter:function(cell,opt,data){
                          if(cell=='true' || cell){
                            return i18n.label_user_holiday_ing;
                          }else{
                            return i18n.label_user_duty_ing;
                          }
                          }},
                        {name:'userState',hidden:true},
                        {name:'job',hidden:true},
                        {name:'password',hidden:true},
                        {name:'officePhone',hidden:true},
                        {name:'orgNo',hidden:true},
                        {name:'description',hidden:true},
                        {name:'fax',hidden:true},
                        {name:'msn',hidden:true},
                        {name:'userCost',hidden:true},
                        {name:'officeAddress',hidden:true},
                        {name:'remark',hidden:true},
                        {name:'tcGroupIds',hidden:true},
                        {name:'dataFlag',hidden:true},
                        {name:'act',align:'center',sortable:false,formatter:wstuo.user.user.userGridFormatter}
                ],
				jsonReader: $.extend(jqGridJsonReader, {id: "userId"}),
				sortname:'userId',
				pager:'#userPager',
				shrinkToFit:false,
				gridComplete:function(){
					$("#userGrid td[aria-describedby=userGrid_act]").attr("title","");
					wstuo.user.user.countTc();//统计技术员
				}
				});
				$("#userGrid").jqGrid(params);
				$("#userGrid").navGrid('#userPager',navGridParams);
				//列表操作项
				$("#t_userGrid").css(jqGridTopStyles);
				$("#t_userGrid").append($('#userTopMenu').html());
				
				//自适应宽度
				setGridWidth("#userGrid", 15);
		},
		
		/** 
		 * @description 保存新用户
		 * */
		addUser:function() {
			var lastName= $('#lastName').val();
			$('#lastName').val(lastName.replace(/[ ]/g,""));
			var firstName= $('#firstName').val();
			$('#firstName').val(firstName.replace(/[ ]/g,""));
			
			//if($('#userWindowForm').form('validate')){
				if(operator=='save'){
					startProcess();
					$.post('user!userExist.action','userDto.userId='+$("#userId").val()+'&userDto.loginName='+$("#loginName").val(),function(data){
						endProcess();
						if(data){
							wstuo.user.user.addUserOpt();
						}else{
							msgShow(i18n.error_userExist,'show');
						}
					});
				}else{
					wstuo.user.user.addUserOpt();
				}
			//}
		},
		
		/** 
		 * @description 编辑保存用户
		 * */
		addUserOpt:function() {
				startProcess();
				var roleIds = $('#userWindowForm').serialize();
				if(roleResourceAuthorize){
					if(roleIds.indexOf('userDto.roleIds')>-1){
						var user_form = $('#userWindowForm').serialize();
						var url = 'user!'+operator+'.action';
						$.post(url, user_form, function(){
							msgShow(i18n.saveSuccess,'show');
							$('#userWindow').dialog('close');
							$('#userGrid').trigger('reloadGrid');
							wstuo.user.user.countTc();//统计技术员
							endProcess();
							//wstuo.config.systemGuide.systemGuide.saveSystemGuide("userGuide");
							wstuo.orgMge.organizationTree.loadOrganizationTreeView('');
						});
					}else{
						endProcess();
						msgShow(i18n.msg_plase_set_role,'show');
					}
				}else{
					var user_form = $('#userWindowForm').serialize();
					var url = 'user!'+operator+'.action';
					$.post(url, user_form, function(){
						msgShow(i18n.saveSuccess,'show');
						$('#userWindow').dialog('close');
						$('#userGrid').trigger('reloadGrid');
						wstuo.user.user.countTc();//统计技术员
						endProcess();
						//wstuo.config.systemGuide.systemGuide.saveSystemGuide("userGuide");
						wstuo.orgMge.organizationTree.loadOrganizationTreeView('');
					});
				}
		},
		
		/**
		 * @description 用户添加窗口
		 */
		
		user_add:function(e){
			//避免同一请求多次访问。
			if(e!=true){return}
				e=false;
				$('#myTab a:first').tab('show');
				$('#myTab a').on('show.bs.tab', function(e) {
					e.preventDefault()
				})
					
					
		    // 清除验证状态
		    wstuo.user.user.removeInvalid();
			$('#loginName,#password,#rpassword').val('');
			$.post('currency!findDefaultCurrency.action',function(data){
				if(data!==null && data!=''){
					$('#userCost_currency').text(data);
				}else{
					$('#userCost_currency').text('RMB');
				}
			});
			
			$('#resetPassword_tr').hide();
			$('#password_tr,#rpassword_tr').show();
			$('#loginName').removeAttr("readonly");
			resetForm('#userWindowForm');
			wstuo.user.user.add_loadRole(0,"roleSet");
			$('#user_companyNo').val(companyNo);
			$('#belongsGroupShowId').empty();
			windows("userWindow",{autoOpen: true,width:550});
			operator = 'save';
			
		},

		/**
		 * @description 编辑用户
		 */
		editUser_aff:function(){
			$('#myTab a').unbind("show.bs.tab");
			checkBeforeEditGrid('#userGrid',wstuo.user.user.editUser);
			
		},
		/**
		 * @description 编辑用户
		 * @param rowId 行的编号
		 */
		editUser_affs:function(rowId){
			var rowData= $("#userGrid").jqGrid('getRowData',rowId);  // 行数据  
			wstuo.user.user.editUser(rowData);
		},
		/**
		 * 用户字段格式化
		 * @param value 字段值
		 */
		userSetInput:function(value){
			if(value!=null)
				return value;
			else
				return "";
		},
		/**
		 * @description 编辑用户窗口
		 * @param rowData  行数据
		 */
		editUser:function(rowData) {
			operator = 'merge';
			$("#user_technicalGroupId").val(rowData.tcGroupIds+",");
			if(rowData.tcGroupNames!=null && rowData.tcGroupNames!=""){
				$("#user_groupName").val(rowData.tcGroupNames+";");
			}else{
				$("#user_groupName").val("");
			}
			$.post('user!findUserDetail.action','userDto.userId='+rowData.userId,function(data){
				$('#userId').val(data.userId);
				/*if(Proxyshow==0){
					Proxyshow=1;
					wstuo.user.user.userProxy(data.userId);//代理人
					$('#link_proxyMain_add').click(wstuo.user.user.proxyadd);
					$('#saveproxyBtn').click(wstuo.user.user.saveprox);
					$('#link_proxyMain_edit').click(function(){wstuo.user.user.proxyedit($("#selectUserByProxy_grid").getGridParam("selrow"))});
					$('#link_proxyMain_delete').click(wstuo.user.user.deleteprox_aff);
					$('#link_proxyMain_search').click(wstuo.user.user.search_aff);
					$('#Search_proxyBtn').click(wstuo.user.user.SearchOpt);
				}else{
					var _postData = $("#selectUserByProxy_grid").jqGrid("getGridParam", "postData");       
					$.extend(_postData, {'proxyDTO.proxieduserId':data.userId});	
					$('#selectUserByProxy_grid').trigger('reloadGrid',[{"page":"1"}]);
				}*/
				$('#loginName').val(data.loginName);
				if(data.firstName!=null && data.firstName!='null')
					$('#firstName').val(data.firstName);
				else
					$('#firstName').val('');
				if(data.lastName!=null && data.lastName!='null')	
					$('#lastName').val(data.lastName);
				else
					$('#lastName').val('');
				if(data.email!=null && data.email!='null')
					$('#email').val(data.email);
				else
					$('#email').val('');
				
				
				$('#password,#rpassword').val(data.password);
				$('#resetPassword_tr').show();
				$('#password_tr,#rpassword_tr').hide();
				

				$('#moblie').val(wstuo.user.user.userSetInput(data.moblie));
				$('#phone').val(wstuo.user.user.userSetInput(data.phone));
				$('#fax').val(wstuo.user.user.userSetInput(data.fax));
				$('#msn').val(wstuo.user.user.userSetInput(data.msn));
				$('#officeAddress').val(wstuo.user.user.userSetInput(data.officeAddress));
				$('#officePhone').val(wstuo.user.user.userSetInput(data.officePhone));
				$('#description').val(wstuo.user.user.userSetInput(data.description));
				$('#remark').val(wstuo.user.user.userSetInput(data.remark));
				$('#userCost').val(data.userCost);
				$('#job').val(wstuo.user.user.userSetInput(data.job));
				$('#user_orgName').val(wstuo.user.user.userSetInput(data.orgName));
				$('#user_orgNo').val(data.orgNo);
				$('#extension').val(wstuo.user.user.userSetInput(data.extension));
				$('#user_position').val(wstuo.user.user.userSetInput(data.position));
				if(data.sex==false){
					$('#user_sex_woman')[0].checked=false;
				}else
				{
					$('#user_sex_man')[0].checked=true;
				}
				
				$('#user_icCard').val(wstuo.user.user.userSetInput(data.icCard));
				$('#user_pinyin').val(wstuo.user.user.userSetInput(data.pinyin));
				$('#user_birthday').val(timeFormatterOnlyData(data.birthday));
				/**
				 * 单选按钮选择项
				 */
				if(data.userState==false){
					$('#userState_true')[0].checked=false;
					$('#userState_flase')[0].checked=true;
				}else
				{
					$('#userState_flase')[0].checked=false;
					$('#userState_true')[0].checked=true;
				}
				$("#userId").attr('name','userDto.userId')
				$('#loginName').attr("readonly",'readonly');
				$('#user_companyNo').val(companyNo);
				$('#lcallCodeOper').val(wstuo.user.user.userSetInput(data.lcallCodeOper));
				$('#remoteHost').val(wstuo.user.user.userSetInput(data.remoteHost));
				$('#remotePort').val(wstuo.user.user.userSetInput(data.remotePort));
				if(data.holidayStatus==true || data.holidayStatus=='true'){
					$('#user_holidayStatus_true')[0].checked=true;
				}else{
					$('#user_holidayStatus_false')[0].checked=false;
				}
				//所属组
				if(data.belongsGroups!=null){
					var _belongsGroups = data.belongsGroups;
					var _content = '';
					for(var i=0;i<_belongsGroups.length;i++){
						_content = '<div id="belongsGroup_[id]">[name]&nbsp;&nbsp;'+
						'<input type="hidden" name="userDto.belongsGroupIds" value="[id1]" />'+
						'<a style="color:red;" onclick="wstuo.orgMge.organizationTreeUtil.belongsGroupRemove([id2])">X</a><div>';
						$('#belongsGroupShowId').append(
								_content.replace('[id]',_belongsGroups[i].orgNo)
								.replace('[id1]',_belongsGroups[i].orgNo)
								.replace('[id2]',_belongsGroups[i].orgNo)
								.replace('[name]',_belongsGroups[i].orgName));
					}
					
				}
			});
			wstuo.user.user.add_loadRole(rowData.userId,"roleSet");
			$('#belongsGroupShowId').empty();
			windows("userWindow",{autoOpen: true,width:550});
			wstuo.user.user.removeInvalid();
		},
		/**
		 * 移除验证
		 */
		removeInvalid : function() {
		    $('#loginName').removeClass('validatebox-invalid'); 
            $('#password').removeClass('validatebox-invalid'); 
            $('#rpassword').removeClass('validatebox-invalid'); 
            $('#lastName').removeClass('validatebox-invalid'); 
            $('#user_orgName').removeClass('validatebox-invalid');   
		},
		
		/**
		 * @description 删除.
		 */
		opt_delete:function(){
			checkBeforeDeleteGrid('#userGrid',wstuo.user.user.opt_deleteInLineMethod);
		},
		
		/**
		 * @description 删除.
		 * @param rowid 行的编号
		 */
		opt_delete_aff:function(rowId){
			msgConfirm(i18n['msg_msg'],'<br/>'+i18n['msg_confirmDelete'],function(){
				wstuo.user.user.opt_deleteInLineMethod(rowId);
			});
		},
		/**
		 * @description 删除Method.
		 * @param rowid 行的编号
		 */
		opt_deleteInLineMethod:function(rowId){
			var arr = $("#userGrid").jqGrid("getRowData",rowId);
			if(arr.dataFlag === "1"){
				msgShow(i18n['msg_canNotDeleteSystemData'],'warning');
				return false;
			}
			var param = $.param({'ids':rowId},true);
			$.post("user!delUser.action", param, function(data){
				if(data==true){
					$('#userGrid').trigger('reloadGrid');
					msgShow(i18n['msg_user_deleteSuccessful'],'show');
					wstuo.user.user.countTc();//统计技术员
				}else if(data=="error"){
					msgShow(i18n['msg_user_deleteErrorKey'],'show');
				}else{
					msgShow(i18n['msg_user_deleteError'],'show');
				}
					
			}, "json");
		},
		
		/**
		 * @description 搜索用户
		 */
		searchUser:function(){
			var userOrg=$('#user_search_orgNo').val();
			var sdata=$('#searchUser form').getForm();
			var postData = $("#userGrid").jqGrid("getGridParam", "postData");
			$.extend(postData,sdata);
			var _url = 'user!find.action';		
			$('#userGrid').jqGrid('setGridParam',{url:_url}).trigger('reloadGrid',[{"page":"1"}]);
		},
		
		/**
		 * @description 打开
		 */
		opt_setRole_aff:function(){
			checkBeforeEditGrid('#userGrid',wstuo.user.user.opt_setRole);
		},
		
		/**
		 * @description 操作项-用户角色确定
		 */
		opt_setRole_affs:function(rowId){
			var rowData= $("#userGrid").jqGrid('getRowData',rowId);  // 行数据  
			wstuo.user.user.opt_setRole(rowData);
		},
		/**
		 * @description 操作项-用户角色设置
		 */
		opt_setRole:function(rowData){
			$('#roleIds').val(rowData.userId);
			wstuo.user.user.add_loadRole(rowData.userId,"roleSetInfo");
			windows('roleSet-win',{width:400});
		},
		/**
		 * @description 操作项-保存(根据用户ID修改角色)
		 */
		updateRoleByUserId:function(){
			var rowIds = $('#roleIds').val();
			if(rowIds=='')
			{
				msgShow(i18n['msg_atLeastChooseOneData'],'show');
			}
			else
			{	
				var _rowIds = rowIds.split(",");
				var param = $.param({'ids':_rowIds},true);
				var user_form = $('#roleSet-win form').serialize();
				if(user_form.indexOf('userDto.roleIds')>-1){
					$.post("user!updateRoleByUserId.action",user_form+'&'+param, function(){
						$('#rolesTb').html("");
						$('#roleSet-win').dialog('close');
						$('#userGrid').trigger('reloadGrid');
						
						msgShow(i18n['msg_user_roleSetSuccessful'],'show');
						wstuo.user.user.countTc();//统计技术员
	
						$('#roleIds').val('')
						
						
					}, "json");
				}else{
					msgShow(i18n['msg_plase_set_role'],'show');
				}		
			}
		},

		/**
		 * @description 加载角色
		 * @param id  编号
		 * @param tab 表格
		 * @param isitsop 是否是外包客户
		 * 
		 */
		add_loadRole:function(id,tab,isitsop){
			loadUserRole=isitsop;
			$("#"+tab+" table").html("");
			$("#"+tab+" table").empty();
			
			if(id!=null){
				if(id==-1){
					id=0;
				}
				wstuo.user.user.getUserRole(id);
				setTimeout(function(){
					wstuo.user.user.getUserRoleAll(tab);
				},500);
			}else{
				setTimeout(function(){
					wstuo.user.user.getUserRoleAll(tab);
				},0);
			}
			
		},
		
		/**
		 * @description 新增页面加载角色复选框
		 * @param id  编号
		 */
		getUserRole:function(id){
				if(id!=0){
					$.post("user!getUserRole.action","id="+id,function(data){
						userRoleIds=data;
					},"json")
				}
		},
		
		
		/**
		 * 得到用户端饿所以角色
		 * @param Tab  表格
		 */
		getUserRoleAll:function(tab){
			$("#"+tab+" table").html('');
			$.post("role!findByState.action",function(data){
				mydata=data;
				this.roleHtml;
				roleHtml="";
				var r = 0;
				var u = 0;
				for(var i=0;i<mydata.length;i++)
				{
					
					if(topCompanyNo!=companyNo || loadUserRole){
						
						if(mydata[i].roleCode=="ROLE_ENDUSER" || mydata[i].roleCode=="ROLE_ITSOP_MANAGEMENT"){
							
							if(r % 2==0){
								roleHtml=roleHtml+"<tr>"
							}
							roleHtml=roleHtml+"<td><label><input type='checkbox' class='roleBox' name='userDto.roleIds' class='userRoleId'"+
							" value='"+mydata[i].roleId+"'";
							if(userRoleIds!=null){
								for(var j=0; j<userRoleIds.length;j++)
								{	
									if(userRoleIds[j].roleId==mydata[i].roleId)
									{
										roleHtml=roleHtml+" checked='checked' ";
									}
								}
							}
							roleHtml=roleHtml+" />"+mydata[i].roleName+"</label></td>"
							r++;
						}
						
					}else{
						if(mydata[i].roleCode!="ROLE_ITSOP_MANAGEMENT"){
							if(u % 2==0){
								roleHtml=roleHtml+"<tr>"
							}
							roleHtml=roleHtml+"<td><label><input type='checkbox' class='roleBox' name='userDto.roleIds' class='userRoleId'"+
							" value='"+mydata[i].roleId+"'";
							if(userRoleIds!=null){
								for(var j=0; j<userRoleIds.length;j++)
								{	
									if(userRoleIds[j].roleId==mydata[i].roleId)
									{
										roleHtml=roleHtml+" checked='checked' ";
									}
								}
							}
							roleHtml=roleHtml+" />"+mydata[i].roleName+"</label></td>";
							u++;
						}
					}
					
				}
				if(topCompanyNo!=companyNo || loadUserRole){
					if(r % 2==1){
						roleHtml+="</tr>"
					}
				}else{
					if(u % 2==1){
						roleHtml+="<td></td>";
					}
				}
				$("#"+tab+" table").html(roleHtml);
				userRoleIds=null;
				
				
				
				
				//选定验证
				/*$('.roleBox').click(function(){
					if(tab!='itsop_user_roles'){
						var roleId=$(this).val();
						if(roleId!=11 && roleId!=12 && ((technicianNumber+1)<=usedTechnicianNumber)){	
							$(this).attr({'checked':false});
							msgShow(i18n['TechnicianLicense_Not_Enough'],'show');
						}							
					}
				});*/
			},"json");
			
			
			loadRoleId=0;
		},
		

		/**
		 * 机构设置保存
		 */
		orgSet_save:function(){
			if($('#ortSet_orgNo').val()==null || $('#ortSet_orgNo').val()==""){
				msgShow(i18n['title_user_selectOrg'],'show');
			}else{	
				var data='id='+$('#ortSet_orgNo').val()+'&str='+$('#userId1').val();
				$.post("user!mergeByOrg.action", data, function(){
					
					msgShow(i18n['msg_operationSuccessful'],'show');
					$('#orgSet-win').dialog('close');
					$('#userGrid').trigger('reloadGrid');
					
					$('#orgSet_orgName').val('');
					$('#ortSet_orgNo').val('');
					$('#userId1').val('');
				}, "json");
			}
		},
		

		/**
		 * 用户角色批量设置窗口
		 * 
		 * */
		userReleSet_win:function(){
			var rowIds = $("#userGrid").getGridParam("selarrrow");

			if(rowIds==""){
				
				msgShow(i18n.msg_atLeastChooseOneData,'show');
				
			}else{	
				
				
				var userId=null;
				
				if(rowIds.length==1){			
					userId=rowIds[0];
				}
				
				
				$('#roleIds').val(rowIds);
				$('#orgName1').val('');
				$('#orgNo1').val('');
				wstuo.user.user.add_loadRole(userId,"roleSetInfo");
				
				windows('roleSet-win',{width:400});
			}
			
		},
		/**
		 * 用户所属机构批量设置
		 * */
		userOrgSet_win:function(){
			$('#orgSet_orgName,#ortSet_orgNo').val('');
			var rowIds = $("#userGrid").getGridParam("selarrrow");
			if(rowIds==""){
				msgShow(i18n['msg_atLeastChooseOneData'],'show');
			}else{

				if(rowIds.length==1){
					$.post('user!findUserDetail.action','userDto.userId='+rowIds,function(data){
						$('#orgSet_orgName').val(data.orgName);
						$('#ortSet_orgNo').val(data.orgNo);
					});
				};
				$('#userId1').val(rowIds);
				windows('orgSet-win',{width:400});
			}
		},

		
		/**
		 * 导出
		 */
		exportUserView:function(){
			$("#searchUser form").submit();
		},
		
		/**
		 * 导入数据.
		 */
		importUserData:function(){
			
			if(language=="en_US"){
				$('#index_import_href').attr('href',"../importFile/en/User.zip");
			}else{
				$('#index_import_href').attr('href',"../importFile/User.zip");
			}
			windows('index_import_excel_window',{width:400});
			$('#index_import_confirm').unbind().click(wstuo.user.user.importUserExcel);
		},
		/**
		 * @descriptionadd 客户端导入数据
		 * */
		importUserExcel:function()
		{
				startProcess();
				$.ajaxFileUpload({
		            url:'user!importUserData.action',
		            secureuri:false,
		            fileElementId:'importUserFile', 
		            dataType:'json',
		            success: function(data,status){
		             	$('#importUserDataWindow').dialog('close');
		            	if(data=="FileNotFound"){
							msgShow(i18n['msg_dc_fileNotExists'],'show');
							endProcess();
						}else if(data=="IOError"){
							msgShow(i18n['msg_dc_importFailure'],'show');
							endProcess();
						}else if(data=="TCNotEnough"){
							msgShow(i18n['TechnicianLicense_Not_Enough'],'show');
							endProcess();
						}else if(data=="ERROR_COMPANY_NAME"){//公司名称输入错误will(20130715)
							msgShow("<br/>"+i18n['ERROR_COMPANY_NAME'],'show');
							endProcess();
						}else{
							msgShow(i18n['msg_dc_dataImportSuccessful']
									+'<br>['+
									data
									.replace('Total',i18n['opertionTotal'])
									.replace('Insert',i18n['newAdd'])
									.replace('Update',i18n['update'])
									.replace('Failure',i18n['failure'])+']'
									,'show');
							endProcess();
						}
		            	$('#userGrid').trigger('reloadGrid');
		            }
		        });
		},
		/**
		 * 加载用户角色
		 */
		loadSearchUserRoles:function(){
			$("#search_user_roles").empty(); 
			$("<option value='0'> -- "+i18n['label_user_selectRole']+" -- </option>").appendTo("#search_user_roles");
			
			$.post("role!find.action?rows=500", function(data){
				if(data!=null && data.data!=null && data.data.length!=0){
					var optionsHTML="";
					
					for(var i=0;i<data.data.length;i++){					
						optionsHTML+="<option value='{0}'>{1}</option>".replace("{0}",data.data[i].roleId).replace("{1}",data.data[i].roleName);
					}					
					$("#search_user_roles").append(optionsHTML);
				}
					
			}, "json");
		},
		/**
		 * 修改密码
		 */
		edit_user_pwd:function(){
			var rowData=$('#userGrid').getRowData($('#userId').val());
			$.post('user!findUserDetail.action','userDto.userId='+$('#userId').val(),function(data){
				$('#editUserPwd_loginName').val(data.loginName);
				$('#editUserPwd_loginName_span').text(data.loginName);
				$('#editUserPwd_oldPassword').val(data.password);
				$('#editUserPwd_newPassword,#editUserPwd_repeatPassword').val('');
				windows('editUserPwd_win',{width:380,height:190});
			})
			
		},
		/**
		 * 登录名去空格
		 * @param  字段值
		 */
		trimLoginName:function(value){
			var reg = /\s/g; 
			$("#user_loginName").val($("#user_loginName").val().replace(reg,""));
		},
		/**
		 * 当前用户角色
		 */
		currentUserRoleCode:function(){
			$.post("user!getCurrentLoginUser.action",function(data){
				for ( var i = 0; i < data.userRoles.length; i++) {
					if( "ROLE_SYSADMIN" == data.userRoles[i].roleCode){
						$("#search_user_state_tr").removeAttr("style");
					}
				}
			});
		},
		/**
		 * 展开或收缩面板.
		 */
		panelCollapseExpand:function(){
			 $(userGrids).each(function(i, g) {
			      setGridWidth(g, 'userDetailInfo_center', 10);
			 });
		},
		
		
		userProxy:function(userId){
			userGrids.push('#selectUserByProxy_grid');
			var params = $.extend({},jqGridParams, {
				url:'proxyAction!findProxyByPage.action',
				postData:{'proxyDTO.proxieduserId':userId},
				colNames:['ID','userId',
				          i18n['lable_proxy_user'],
				          i18n['title_startTime'],
				          i18n['title_endTime'],
				          i18n['title_snmp_state']
				],
			 	colModel:[
			 	          {name:'proxyId',align:'center',width:45,hidden:true},
			 	          {name:'userId',align:'center',width:45,hidden:true},
			 	          {name:'userName',index:'userAgent',align:'center',width:100},
			 	          {name:'startTime',align:'center',width:80},
			 	          {name:'endTime',align:'center',width:80},
			 	         {name:'proxyState',align:'center',width:50,sortable:false,formatter:wstuo.user.user.isToproxyState}
			 	],
				jsonReader: $.extend(jqGridJsonReader, {id: "proxyId"}),
				sortname:'proxyId',
				pager:'#selectUserByProxy_pager'
				});
				$("#selectUserByProxy_grid").jqGrid(params);
				$("#selectUserByProxy_grid").navGrid('#selectUserByProxy_pager',navGridParams);
				//列表操作项
				$("#t_selectUserByProxy_grid").css(jqGridTopStyles);
				$("#t_selectUserByProxy_grid").append($('#proxyMainToolbar').html());
				//自适应宽度
				setGridWidth("#selectUserByProxy_grid","userDetailInfo_center",8);
		},
		isToproxyState:function(cell,event,data){
		  if(cell){
			  return i18n['disable'];
		  }else{
			  return i18n['enable'];
		  }
		},
		proxyadd:function(){
			ProxyType=0;
			$('#proxy_add_proxyTypeId').val('');
			$('#proxyUserId').val('');
			$('#proxy_add_proxyName').val('');
			$('#proxy_add_startTime').val('');
			$('#proxy_add_endTime').val('');
			windows('proxyMainAddWin',{width:380,height:190});
		},
		proxyedit:function(rowId){
			ProxyType=1;
			if(rowId==null){
				msgShow(i18n['msg_atLeastChooseOneData'],'show');
			}else{
				var data = $("#selectUserByProxy_grid").getRowData(rowId);
				$('#proxy_add_proxyTypeId').val(data.proxyId);
				$('#proxyUserId').val(data.userId);
				$('#proxy_add_proxyName').val(data.userName);
				$('#proxy_add_startTime').val(data.startTime);
				$('#proxy_add_endTime').val(data.endTime);
				windows('proxyMainAddWin',{width:380,height:190});
			}
		},
		saveprox:function(){
			$('#proxy_add_proxieduserId').val($("#userGrid").getGridParam("selrow"));
			if($('#proxyMainAddWin form').form('validate')){
				var _frm = $('#proxyMainAddWin form').serialize();
				var url = 'proxyAction!saveProxy.action';
				if(ProxyType==1){
					url = 'proxyAction!editProxy.action';
				}
				//调用
				startProcess();
				$.post(url,_frm, function(){
					msgShow(i18n['saveSuccess'],'show');
					$('#proxyMainAddWin').dialog('close');
					$('#selectUserByProxy_grid').trigger('reloadGrid');
					endProcess();
				});
			}
		},
		/**
		 * @description 判断是否选择要删除
		 */
		deleteprox_aff:function(){
			checkBeforeDeleteGrid('#selectUserByProxy_grid', wstuo.user.user.deleteproxOpt);
		},
		/**
		 * @description 删除操作
		 * @param rowids  行编号
		 */
		deleteproxOpt:function(rowsId){
			var url="proxyAction!deleteProxy.action";
			var param = $.param({'ids':rowsId},true);
			$.post(url, param, function()
			{
				msgShow(i18n['msg_deleteSuccessful'],'show');
				$('#selectUserByProxy_grid').trigger('reloadGrid');
			}, "json");	
		},
		/**
		 * 查询
		 */
		search_aff:function(){
			$('#Search_proxyUserId').val('');
			$('#proxy_Search_proxyName').val('');
			$('#proxy_Search_proxieduserId').val($("#userGrid").getGridParam("selrow"));
			windows('Search_proxyMainWin',{width:380,height:160});
		},
		/**
		 * 查询
		 */
		SearchOpt:function(){
			var sdata=$('#Search_proxyMainWin form').getForm();
			var postData = $("#selectUserByProxy_grid").jqGrid("getGridParam", "postData");
			$.extend(postData,sdata);
			var _url = 'proxyAction!findProxyByPage.action';
			$('#selectUserByProxy_grid').jqGrid('setGridParam',{url:_url}).trigger('reloadGrid',[{"page":"1"}]);
		},
		/**
		 * 点击右边的机构进行查询机构下面的用户
		 */
		search_UserGrid : function(treeId,companyNo){
			$(treeId).jstree({
				json_data:{
					ajax: {
						url : "organization!findAll.action?companyNo="+companyNo,
						data:function(n){
					    	  return {'parentOrgNo':n.attr ? n.attr("orgNo").replace("node_",""):0};//types is in action
						},
						cache: false
					}
				},
				plugins : ["themes", "json_data", "ui"]

			})
			.bind('select_node.jstree',function(e,data){
				var orgNo = data.rslt.obj.attr("orgNo");
				var orgType = data.rslt.obj.attr("orgType");
				var postData = $("#userGrid").jqGrid("getGridParam", "postData");
				if(orgType!="innerPanel"&&orgType!="servicePanel"){
					var _postData={'userQueryDto.orgNo':orgNo,'userQueryDto.companyNo':companyNo};
					var _url = 'user!find.action';
					if(orgType=="company")
						_postData={'userQueryDto.orgNo':"",'userQueryDto.companyNo':companyNo};
					$.extend(postData,_postData);
					$('#userGrid').jqGrid('setGridParam',{url:_url}).trigger('reloadGrid',[{"page":"1"}]);
				}
			});
		},
		validNextPage : function(e){
			//$('#myTab a:first').unbind("show.bs.tab");
			var validTab=$("#myTab li:eq('"+(e-1)+"') a").attr("href");
			 var len = $(validTab+" input[required='true']").length;
			 if(len==0){
				 //$("#myTab li:eq('"+e+"') a").unbind("show.bs.tab");
				 $("#myTab li:eq('"+e+"') a").tab('show');
			 }
			$(validTab+" input[required='true']").each(function(i,v){
				if(!$(v).val()){
					$(v).attr("data-placement","bottom");
					$(v).attr("data-toggle","tooltip");
					$(v).attr("data-original-title","输入有误");
					$(v).tooltip();
					$(v).focus();
					return false;
				}
				if(len==(i+1)){
					$('#myTab a').unbind("show.bs.tab");
					//$("#myTab li:eq('"+e+"') a").unbind("show.bs.tab");
					$("#myTab li:eq('"+e+"') a").tab('show');
				}
				
			});
			
		},
		validAbovePage : function(e){
			
			$("#myTab li:eq("+e+") a").tab('show');
		},
		/**
		 * 初始化加载
		 */
		init:function(){
			wstuo.user.user.showUserGrid();
			//setTimeout(wstuo.user.user.fitProblemGrids,0);
			//绑定日期控件
			DatePicker97(['#user_birthday']);
			//bindControl('#proxy_add_startTime,#proxy_add_endTime');
			$("#userMain_loading").hide();
			$("#userMain_content").show();
			wstuo.user.user.currentUserRoleCode();
			$('#userGrid_add').click(wstuo.user.user.user_add);
			$('#userGrid_edit').click(wstuo.user.user.editUser_aff);
			$('#userGrid_delete').click(wstuo.user.user.opt_delete);
			$('#userGrid_search').click(function(){
				if(user_search_selectData_flag){
					wstuo.user.user.loadSearchUserRoles();
					user_search_selectData_flag=false;
				}
				windows('searchUser',{width:400});
			});
			$('#user_link_search').click(wstuo.user.user.searchUser);
			$('#link_user_role').click(wstuo.user.user.userReleSet_win);
			$('#link_roleSet_save').click(wstuo.user.user.updateRoleByUserId);
			$('#userGrid_org').click(wstuo.user.user.userOrgSet_win);
			$('#link_orgSet_save').click(wstuo.user.user.orgSet_save);
			$('#user_orgName').click(function(){
			    $('#user_orgName').blur();
				wstuo.orgMge.organizationTreeUtil.selectOrg('#userGroup_win','#userGroupTree','#user_orgName','#user_orgNo',companyNo,function(orgNo,orgName,orgType){
					var _content = '<div id="belongsGroup_[id]">[name]&nbsp;&nbsp;'+
					'<input type="hidden" name="userDto.belongsGroupIds" value="[id1]" />'+
					'<a style="color:red;" onclick="wstuo.orgMge.organizationTreeUtil.belongsGroupRemove([id2])">X</a><div>';
					if(orgType != 'innerPanel' && orgType != 'servicePanel'){
						if($('#belongsGroup_'+orgNo).html()==null){
							$('#belongsGroupShowId').append(
									_content.replace('[id]',orgNo)
									.replace('[id1]',orgNo)
									.replace('[id2]',orgNo)
									.replace('[name]',orgName));
						}
					}
				});
			});
			$('#orgSet_orgName').click(function(){
				wstuo.orgMge.organizationTreeUtil.showAll_2('#userGroup_win','#userGroupTree','#orgSet_orgName','#ortSet_orgNo',companyNo);
			});
			$('#user_search_orgName').click(function(){
				wstuo.orgMge.organizationTreeUtil.showAll_2('#userGroup_win','#userGroupTree','#user_search_orgName','#user_search_orgNo',companyNo);
			});
			$('#search_user_belongsGroup').click(function(){
				wstuo.orgMge.organizationTreeUtil.showAll_3('#userGroup_win','#userGroupTree','#search_user_belongsGroup','#user_search_orgNo',companyNo);
			});
			$('#link_user_password_reset').click(function(){wstuo.user.userPwdUpdate.userPasswordReset($('#loginName').val())});
			$('#userGrid_Import').click(wstuo.user.user.importUserData);
			$('#userGrid_Export').click(wstuo.user.user.exportUserView);
			$('#link_edit_user_pwd').click(wstuo.user.user.edit_user_pwd);//修改密码
			$('#edit_user_pwd_but').click(wstuo.user.userPwdUpdate.userPwdUpdate_manage);//确定修改密码
			/*$('#user_groupName').click(function(){
				common.security.selectTechnicalGroup.selectTechmentGroup('user_groupName','user_technicalGroupId');
			});*/
			//选择所属组
			$('#selectBelongsGroupBut').click(function(){
				wstuo.includes.loadCategoryIncludesFile();
				$('#index_selectORG_window').attr('title',i18n.label_userOwnerGroup);
				wstuo.orgMge.organizationTreeUtil.selectBelongsGroup('belongsGroupShowId',companyNo);
			});
			wstuo.user.user.search_UserGrid("#user_orgTreeDIV",companyNo);
		}
	}
}();
/**载入**/
$(document).ready(wstuo.user.user.init);
